# == Schema Info
# Schema version: 20091029102158
#
# Table name: structures
#
#  id             :integer(4)      not null, primary key
#  parent_id      :integer(4)
#  cached_level   :integer(4)      default(0)
#  contents_count :integer(4)      default(0)
#  is_visible     :boolean(1)      default(TRUE)
#  kind           :integer(1)      default(0)
#  lft            :integer(4)      default(0)
#  position       :integer(2)      default(0)
#  posts_count    :integer(4)      default(0)
#  rgt            :integer(4)      default(0)
#  slug           :string(25)      not null
#  title          :string(255)     not null
#  created_at     :datetime
#  updated_at     :datetime

class Structure < ActiveRecord::Base
  include HeaderTools
  
  acts_as_nested_set
  
  acts_as_enum :kind, [:page, :posts, :main, :help, :signup, :gallery, :services, :coaches ]
  acts_as_enum :css_class, [:b4, :b3, :b2, :b1, :b5, :b6]
  
  CSS_CLASS_NAMES = [ ['Листья', :b4],
                      ['Синий', :b3],
                      ['Розовый', :b2],
                      ['Зеленый', :b1],
											['Окна', :b5],
											['Ягоды', :b6] ]
  
  translates :title
  
  validates_presence_of :title
  validates_numericality_of :position, :only_integer => true
  
  has_slug :prepend_id=>false
  
  has_one :page, :dependent=>:destroy
  has_many :posts, :dependent=>:destroy
  has_one :slider, :class_name=> "AttachmentFile", :as=>:assetable, :dependent=>:destroy
  has_many :photos, :as=>:assetable, :dependent=>:destroy
  
  acts_as_uploaded :slider
  
  #after_move :make_parent_kind
  
  named_scope :visible, :conditions=>"is_visible = 1", :order=>"position"
  named_scope :by_level, lambda { |*args| { :conditions=>["cached_level = ?", (args.first || 0)], :order=>"lft" } }
  named_scope :by_kind, lambda { |*args| { :conditions=>["kind = ?", self.kind(args.first) ] } }
  #named_scope :by_position, lambda { |*args| { :conditions=>["position = ?", self.position(args.first) ] } }
  
  private
  
  def make_parent_kind
    self.update_attribute(:kind, self.parent.kind) if self.child? && !self.parent.root?
  end
end
